import datetime

from django.db import models
from django.contrib.auth import get_user_model

from goods.models import Goods
# from users.models import UserProfile
User = get_user_model()
# Create your models here.


class ShoppingCart(models.Model):
    """
    购物车
    """
    user = models.ForeignKey(User, verbose_name="用户")
    goods = models.ForeignKey(Goods, verbose_name="商品")
    nums = models.IntegerField(verbose_name="购买数量", default=0)
    add_time = models.DateTimeField(verbose_name="添加时间", default=datetime.datetime.now)

    class Meta:
        verbose_name = "购物车"
        verbose_name_plural = verbose_name
        unique_together = ('user', 'goods')

    def __str__(self):
        return "{goods_name}({nums})".format(goods_name=self.goods.name, nums=self.nums)


class OrderInfo(models.Model):
    """
    订单
    """
    PAY_STATUS_CHOICES = (
        ("WAIT_BUYER_PAY", "交易创建"),
        ("TRADE_CLOSED", "超时关闭"),
        ("TRADE_SUCCESS", "成功"),
        ("TRADE_FINISHED", "交易结束"),
        ("paying", "待支付"),
    )

    # PAY_TYPE_CHOICES = (
    #     ("alipay", "支付宝"),
    #     ("wechat", "微信")
    # )
    user = models.ForeignKey(User, verbose_name="用户")
    order_sn = models.CharField(verbose_name="订单号", null=True, blank=True, max_length=30, unique=True)
    # trade_no是要传给第三方支付的，然后用trade_no和第三方支付返回的数据进行关联
    trade_no = models.CharField(verbose_name="交易编号", max_length=100, unique=True, null=True, blank=True)
    pay_status = models.CharField(verbose_name="订单状态", choices=PAY_STATUS_CHOICES, default="paying", max_length=30)
    post_script = models.CharField(verbose_name="订单留言", max_length=200, null=True, blank=True)
    order_mount= models.FloatField(verbose_name="订单金额", default=0.0)
    pay_time = models.DateTimeField(verbose_name="支付时间", null=True, blank=True)

    # 用户信息,这里不用外键的原因是，避免用户修改地址后，历史订单跟着改变
    address = models.CharField(verbose_name="收货地址", max_length=100, default="")
    # 签收人信息
    signer_name = models.CharField(verbose_name="签收人姓名", max_length=20, default="")
    signer_mobile = models.CharField(verbose_name="签收人手机", max_length=11)

    add_time = models.DateTimeField(verbose_name="添加时间", default=datetime.datetime.now)

    class Meta:
        verbose_name = "订单"
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.order_sn)


class OrderGoods(models.Model):
    """
    订单的商品详情
    一个订单一般会包括好多商品（1对多的关系），因此需要单独的一张表存储
    """
    order = models.ForeignKey(OrderInfo, verbose_name="订单信息", related_name="goods")
    goods = models.ForeignKey(Goods, verbose_name="商品")
    goods_num = models.IntegerField(verbose_name="商品数量", default=0)
    add_time = models.DateTimeField(verbose_name="添加时间", default=datetime.datetime.now)

    class Meta:
        verbose_name = "订单商品"
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.order.order_sn)
